var fs = require('fs');
var myArgs = process.argv.slice(1);

var content = fs.readFileSync(myArgs[1], 'utf8');
var nbrContact = 0, answer;
var contact = [], nom = [], tel = [], adresse = [], org = [];


for (var i = 1; i <= content.length; i++) {
    var fin = content.indexOf("END:VCARD") + 9;
    contact[i] = content.substring(0, fin);
    content = content.replace(contact[i], "");
    nbrContact++;
}

//définition blocs contacts
for (i = 1; i <= nbrContact; i++) {
    //recuperation nom
    posNom = contact[i].indexOf("FN:") + 3;
    posFinNom = contact[i].indexOf("TEL;") - 1;
    nom[i] = contact[i].substring(posNom, posFinNom);

    //recuperation numéro de téléphone
    posTel1 = contact[i].indexOf("CELL:") + 5;
    posTel1Fin = contact[i].indexOf("EMAIL") - 1;
    tel[i] = contact[i].substring(posTel1, posTel1Fin);
    tel[i] = tel[i].replace("HOME:", "");
    tel[i] = tel[i].replace("PREF:", "");

    posAdresse = contact[i].indexOf("EMAIL") + 6;
    posAdresseFin = contact[i].indexOf("ORG") - 1;

    //recuperation adresse email
    adresse[i] = contact[i].substring(posAdresse, posAdresseFin);
    adresse[i] = adresse[i].replace("HOME:", "");
    adresse[i] = adresse[i].replace("PREF:", "");

    //recuperation Societe
    posTel1 = contact[i].indexOf("ORG:") + 4;
    posTel1Fin = contact[i].indexOf("END:VCARD") - 1;
    org[i] = contact[i].substring(posTel1, posTel1Fin);

}
var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

vcfToCsv();
console.log("Exporte vers 'output.csv'");
setTimeout(rl.close(), 1000);

function vcfToCsv() {
    setTimeout(fs.writeFile('output.csv', '', function(err) {
        if (err)
            throw err;
    }), 1000);
    setTimeout(fs.appendFile('output.csv', '"Nom";"Tel";"Email";"Org"\r\n', function(err) {
        if (err)
            throw err;
    }), 1000);

    for (i = 1; i <= nbrContact; i++) {
        setTimeout(fs.appendFile('output.csv', '"' + nom[i] + '";"' + tel[i] + '";"' + adresse[i] + '";"' + org[i] + '"\r\n', function(err) {
            if (err)
                throw err;
        }), 1000);

    }


}
